package leetcode

/*
 * @lc app=leetcode.cn id=92 lang=golang
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseBetween2(head *ListNode, left int, right int) *ListNode {
	if head == nil {
		return head
	}
	dummyNode := &ListNode{Next: head}
	curr := 1
	leftEnd := dummyNode
	for ; curr < left; curr++ {
		leftEnd = leftEnd.Next
	}
	pre, node := leftEnd, leftEnd.Next
	for ; curr <= right; curr++ {
		pre, node.Next, node = node, pre, node.Next
	}
	leftEnd.Next.Next, leftEnd.Next = node, pre
	return dummyNode.Next
}

// 官方
func reverseBetween(head *ListNode, left int, right int) *ListNode {
	dummyNode := &ListNode{Next: head}
	curr := 1
	leftEnd := dummyNode
	for ; curr < left; curr++ {
		leftEnd = leftEnd.Next
	}
	node := leftEnd.Next
	for ; curr < right; curr++ {
		leftEnd.Next, node.Next.Next, node.Next = node.Next, leftEnd.Next, node.Next.Next
	}
	return dummyNode.Next
}

// @lc code=end
